package org.alex.nettychat.netty.custom.handler;

import io.netty.channel.Channel;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;
import io.netty.channel.group.ChannelGroup;
import org.alex.nettychat.netty.custom.protocol.GetGroupInfoRequestPacket;
import org.alex.nettychat.netty.custom.protocol.GetGroupInfoResponsePacket;
import org.alex.nettychat.netty.custom.utils.SessionUtil;

import java.util.ArrayList;
import java.util.List;

/**
 * 创建群里请求
 */
public class GetGroupInfoRequestHandler extends SimpleChannelInboundHandler<GetGroupInfoRequestPacket> {

    @Override
    protected void channelRead0(ChannelHandlerContext ctx, GetGroupInfoRequestPacket requestPacket) throws Exception {

        // 获取群
        Integer groupId = requestPacket.getGroupId();
        ChannelGroup channelGroup = SessionUtil.getChannelGroup(groupId);
        List<String> usernameList = new ArrayList<>();
        for (Channel channel : channelGroup) {
            usernameList.add(SessionUtil.getSession(channel).getUserName());
        }
        // 构造结果集
        GetGroupInfoResponsePacket responsePacket = new GetGroupInfoResponsePacket();
        responsePacket.setUsernameList(usernameList);
        ctx.channel().writeAndFlush(responsePacket);
    }
}
